#!/bin/sh
#
# Run MiniJade
#  

EXAMPLE="minijade-alone"
PROFILE="false"
DEBUG="false"
MODE="intercative"
JAVA=java

while getopts "e:d:p:sich" option
do
case $option in
d ) DEBUG="true"
    DEBUGPORT=$OPTARG
    ;;
p ) PROFILE="true"
    PROFLOGFILE=$OPTARG
    ;;
c ) MODE="console"
    ;;
s ) MODE="server" 
    ;;
i ) MODE="intercative" 
    ;;
e ) EXAMPLE=$OPTARG 
    ;;
h ) echo "minijadectl [OPTION]"
    echo "  -c                 run a console"
    echo "  -s                 run MiniJade in a server mode"
    echo "  -i                 run MiniJade in a interactive mode (default)"
    echo "  -d <port>          start JVM with remote debug options on port <port>"
    echo "  -p <log file>      start JVM with profiling options"
    echo "  -e <example name>  the name of the example to launch"
    exit 0
    ;;
* ) echo "try minijadectl -h for more information." 
    exit 1
    ;;
esac
done

if [ "$EXAMPLE" = "" ]; then
  echo "example not set"
  echo "try minijadectl -h for more information."
  exit 1
fi

ok="false"
for i in `ls examples`
do
  if [ "$EXAMPLE" = "$i" ]; then
    ok="true"
  fi
done

if [ "$ok" = "false" ]; then
  echo "example "$EXAMPLE" not found in ./examples/"
  exit 1
fi

cygwin=false
linux=false
darwin=false

case "`uname`" in
CYGWIN*) cygwin=true;;
Linux*) linux=true;;
Darwin*) darwin=true;;
esac

if $linux; then
  SEPAR=':'
fi

if $darwin; then
  SEPAR=':'
fi

if $cygwin; then
  SEPAR=';'
fi

JVMOPTS=""

if [ "$DEBUG" = "true" ]; then
  if [ "$DEBUGPORT" = "" ]; then
    DEBUGPORT=8787
  fi
  JVMOPTS="$JVMOPTS"' -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address='"$DEBUGPORT"',server=y,suspend=n'
fi

if [ "$PROFILE" = "true" ]; then
  JVMOPTS="$JVMOPTS"' -Xrunhprof:cpu=samples,depth=12,interval=100,file='"$PROFLOGFILE"
fi

JVMOPTS="$JVMOPTS"' -Djline.terminal=jline.UnixTerminal' 
JVMOPTS="$JVMOPTS"' -enableassertions'
JVMOPTS="$JVMOPTS"' -Dfractal.provider=fr.jade.fraclite.FracLite'
JVMOPTS="$JVMOPTS"' -Dfraclite.config=ReflexFracLite.xml'

for i in `ls dist/lib/`
do
  if [ "$CLASSPATH" = "" ]; then
    CLASSPATH=dist/lib/"$i"
  else
    CLASSPATH="$CLASSPATH""$SEPAR"dist/lib/"$i"
  fi
done

if [ "$EXAMPLE" != "" ]; then
  for i in `ls examples/$EXAMPLE/dist/lib/`
  do
    CLASSPATH="$CLASSPATH""$SEPAR"examples/$EXAMPLE/dist/lib/"$i"
  done
  CLASSPATH="$CLASSPATH""$SEPAR"examples/$EXAMPLE/etc
fi

if [ "$MODE" = "console" ]; then
  MAIN=fr.jade.console.core.Launcher
  ARGS=''
elif [ "$MODE" = "server" ]; then
  MAIN=fr.jade.console.cmd.Boot
  ARGS='boot fr.jade.Jade'
else
  MAIN=fr.jade.console.core.Launcher
  ARGS='boot fr.jade.Jade'
fi

stty -icanon min 1 -echo
$JAVA $JVMOPTS -classpath $CLASSPATH $MAIN "$ARGS"
stty icanon echo
